package cn.springcloud.fix.common.core.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class HeaderLocal {

    private static ThreadLocal<HeaderInfo> HEADERLOCAL = new ThreadLocal<>();

    private HeaderLocal() {
    }

    public static HeaderInfo getHeaderInfo() {
        return HEADERLOCAL.get();
    }

    public static void setHeaderInfo(HeaderInfo headerInfo) {
        log.info("[Set HeaderInfo]:{}", JSON.toJSONString(headerInfo));
        HEADERLOCAL.set(headerInfo);
    }

    /**
     * 删除头部信息
     */
    public static void delHeader() {
        HEADERLOCAL.remove();
    }

    /**
     * 获取Header头部信息
     */
    public static HeaderInfo getHeaderInfo(HttpServletRequest httpServletRequest) {
        try {
            String header = httpServletRequest.getHeader("header");
            log.info("【header】:{}", header);
            if (StringUtils.isEmpty(header)) {
                HEADERLOCAL.set(null);
                return null;
            }
            HeaderInfo headerInfo = JSONObject.parseObject(header, HeaderInfo.class);
            log.info("【headerInfo】:{}", JSON.toJSONString(headerInfo));
            HEADERLOCAL.set(headerInfo);
            return headerInfo;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            HEADERLOCAL.set(null);
            return null;
        }
    }
}
